<?php
/**
 * Created by PhpStorm.
 * User: hwy
 * Date: 2020/6/17
 * Time: 21:30
 */

namespace App\Models;


use App\Services\SendMailService;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

class StockArticle extends BaseModel
{
    protected $table = "stock_article";
    /**
     * 可以被批量赋值的属性.
     *
     * @var array
     */
    protected $fillable = [ 'id', 'title', 'content', 'subjectId', 'created_at', 'updated_at' ];

    public function has_one_article_stock_content()
    {
        return $this->hasOne(StockArticleContent::class, 'article_stock_id', 'id');
    }



    static public function monitorStock()
    {
        $now    = Carbon::now();
        $hours  = $now->hour;
        $minute = $now->minute;

        if (( $hours < 9 ) || $hours > 15 || ( $hours = 9 && $minute < 20 )) {
            return true;
        }

        $stock_real_data = Cache::get('stock_real_data');

        if (empty($stock_real_data)) {
            return true;
        }

        $infos = [];
        foreach ( $stock_real_data as $key => $val ) {
            if (!empty($val)) {
                $stock_check = [];
                if (Cache::has('check_' . $val[2])) {
                    $check_code = Cache::get('check_' . $val[2]);
//                    $val[32] = 0;
                    if ($val[32] - $check_code > 2 || $val[32] - $check_code < -2) {
                        $info           = [];
                        $info['name']   = $val[1];
                        $info['key']    = $val[2];
                        $info['cost']   = $val[3];
                        $info['zf']     = $val[32];
                        $info['old_zf'] = $check_code;
                        Cache::put('check_' . $val[2], $val[32]);
                        $infos[] = $info;
                    }

                } else {
                    Cache::put('check_' . $val[2], $val[32]);
                }


            }
        }

        if (!empty($infos)) {
            $title     = 'stock信息';
            $content   = 'stock信息';
            $email_arr = [ '429208948@qq.com' ];
            $send      = [
                'info' => $infos
            ];
            $view      = 'emails.stock';

            $send_email = SendMailService::send(2, $title, $content, $email_arr, $send, $view);
        }


    }

}
